//
//  WmcCloudAlbumSearchResultVM.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/5/14.
//

import Foundation

extension WmcCloudAlbumSearchResultVM {
    
    enum SearchType {
        /// 个人相册搜索
        case personalAlbumSearch
        /// 团队相册搜索
        case teamAlbumSearch
    }
}

class WmcCloudAlbumSearchResultVM: WmcBaseVM {
    // Lifecycle
    
    required init() {
        super.init()
        self.pageSize = 20
    }

    // Internal
    /// 新增字段 接口调用时候区分团队和个人, 默认个人类型
    var searchType: SearchType? = .personalAlbumSearch
    
    /// 水印类型请求参数
    var watermarks: [WmcSelectWatermarkModel] = []

    /// 开始时间
    var startDate: String?

    /// 结束时间
    var endDate: String?

    /// 照片总数
    var total: Int = 0

    /// 界面显示的列表数据
    private(set) var dataSource: [WmcMediaPhotoModel] = []
    /// 预览页面数据
    private(set) var browserDataSource: [WmcMedia] = []
    /// 是否没有数据
    private(set) var hasNoMore: Bool = false

    func refresh(completion: @escaping ([WmcMediaPhotoModel]) -> Void, failure: @escaping (Error) -> Void) {
        fetchWatermarkPhotoList(pageIndex: 1, pageSize: pageSize) { [weak self] list in
            guard let weakSelf = self else { return }

            weakSelf.page = 2
            weakSelf.hasNoMore = list.count < weakSelf.pageSize
            weakSelf.originalDataSource = list
            weakSelf.dataSource = list
            var temp: [WmcMedia] = []
            weakSelf.originalDataSource.forEach { model in
                if model.resourceType == 0 {
                    temp.append(WmcImage(url: model.url))
                } else if model.resourceType == 1 {
                    temp.append(WmcVideo(url: model.url))
                }
            }
            weakSelf.browserDataSource = temp
            completion(list)
        } failure: { error in
            failure(error)
        }
    }

    func loadMore(completion: @escaping () -> Void, failure: @escaping (Error) -> Void) {
        fetchWatermarkPhotoList(pageIndex: page, pageSize: pageSize) { [weak self] list in
            guard let weakSelf = self else { return }

            weakSelf.page += 1
            weakSelf.hasNoMore = list.count < weakSelf.pageSize
            weakSelf.originalDataSource.append(contentsOf: list)
            weakSelf.dataSource.append(contentsOf: list)
            var temp: [WmcMedia] = []
            weakSelf.originalDataSource.forEach { model in
                if model.resourceType == 0 {
                    temp.append(WmcImage(url: model.url))
                } else if model.resourceType == 1 {
                    temp.append(WmcVideo(url: model.url))
                }
            }
            weakSelf.browserDataSource = temp
            completion()
        } failure: { error in
            failure(error)
        }
    }

    func deleteImage(indexPath: IndexPath, index: Int, success: @escaping () -> Void, failure: @escaping (Error) -> Void) {
        if indexPath.section < dataSource.count, index < browserDataSource.count {
            if indexPath.row < dataSource.count {
                let model = dataSource[indexPath.row]
                WmcMediaAlbumAPI.deletePhoto(id: model.id).subscribe(onNext: { [weak self] r in
                    guard let weakSelf = self else { return }
                    weakSelf.dataSource.remove(at: indexPath.row)
                    weakSelf.originalDataSource.remove(at: index)
                    weakSelf.browserDataSource.remove(at: index)
                    success()
                }, onError: { error in
                    failure(error)
                }).disposed(by: rx.disposeBag)
            }
        }
    }
    
    func fetchVideoShare(index: Int, success: @escaping (WmcMediaShareModel) -> Void, failure: @escaping (Error?) -> Void) {
        if index < originalDataSource.count {
            let model = originalDataSource[index]
            WmcMediaAlbumAPI.fetchVideoShareInfo(id: model.id).subscribe(onNext: { r in
                success(r)
            }, onError: { error in
                failure(error)
            }).disposed(by: rx.disposeBag)
        } else {
            failure(nil)
        }
    }

    // Private

    /// 接口返回的原始数据
    private var originalDataSource: [WmcMediaPhotoModel] = []

    private func fetchWatermarkPhotoList(pageIndex: Int, pageSize: Int, completion: @escaping ([WmcMediaPhotoModel]) -> Void, failure: @escaping (Error) -> Void) {        
        var ids: [Int] = []
        watermarks.forEach { model in
            ids.append(model.data.wmId)
        }
        
        let startDate = self.startDate?.replacingOccurrences(of: ".", with: "-")
        let endDate = self.endDate?.replacingOccurrences(of: ".", with: "-")
                
        WmcMediaAlbumAPI.fetchPhotoList(page: pageIndex, pageSize: pageSize, wmIds: ids, startDate: startDate, endDate: endDate) { [weak self] data in
            guard let weakSelf = self else { return }
            weakSelf.total = data.total
            completion(data.list)
        } failure: { error in
            failure(error)
        }
    }
}
